const BaseRest = require('../rest.js')

module.exports = class extends BaseRest {
  async apiListAction () {
    const {page, pageSize} = this.ctx.query
    const api = this.modelInstance
    const apiPage = await api.page(page, pageSize).countSelect()
    this.success(apiPage)
  }

  async roleApiListAction () {
    const {roleId, page, pageSize, actionPath} = this.get()
    let where = {role_id: roleId}
    if (actionPath !== '') {
      where.path = ['LIKE', `%${actionPath}%`]
    }
    let actions = await this.modelInstance.join({
      table: 'role_action',
      join: 'inner',
      as: 'c',
      on: {id: 'action_id'}
    }).where(where).page({page, pageSize}).countSelect()
    this.success(actions)
  }

  async notRoleApiListAction () {
    const {roleId, page, pageSize, actionPath} = this.get()
    let actions = await this.model('role_action').where({role_id: roleId}).field('action_id').select()
    let where = {}
    if (actions.length !== 0) {
      where.id = ['NOTIN', this.getValueList(actions, 'action_id')]
    }
    if (actionPath !== '') {
      where.path = ['LIKE', `%${actionPath}%`]
    }
    actions = await this.modelInstance.where(where).page(page, pageSize).countSelect();
    this.success(actions)
  }

  async saveRoleApiAction () {
    const {roleId, actions} = this.post()
    let actionList = []
    actions.forEach(item => {
      let action = {role_id: roleId}
      Object.assign(action, item)
      actionList.push(action)
    })
    const ids = await this.model('role_action').addMany(actionList)
    this.success(ids)
  }

  async deleteRoleApiAction () {
    const {roleId, actionIds} = this.post()
    let rows = await this.model('role_action').where({role_id: roleId, action_id: ['IN', actionIds]}).delete()
    this.success(rows)
  }
}
